/**
 * @author wangxiaowei
 * 组织部发文列表
 */
var sort = null;
var grid = null;

function initgenzonglist(){
	initselectusertreechecktask();		
var colModel = new Ext.grid.ColumnModel([
		{header:'姓名',dataIndex:'username',menuDisabled : true},
		{header:'环节名称',dataIndex:'taskname',menuDisabled : true},
		{header:'完成时间',dataIndex:'time',menuDisabled : true},
		{header:'操作',dataIndex:'operate',menuDisabled : true}
	]);
	var url = Ext.get('url').getValue();
	sort = new Ext.data.JsonStore({
		url:url,
		fields:['username','taskname','time','operate'],
		root:'root',
		totalProperty:'totalProperty'
	});
	var bbar = new Ext.PagingToolbar({
		pageSize:23,
		store:sort,
		displayInfo:true,
		emptyMsg:'没有记录'
	});
	 grid = new Ext.grid.GridPanel({
		title:'行政发文跟踪列表',
		cm:colModel,
		tbar:[{
			 text: '返回',
             iconCls: 'silk-add',
              handler:function(){
             	window.location.href=Ext.get('historyurl').getValue();
             }
		}
		,{
			 text: '追加封发人',
             iconCls: 'silk-addfengfa',
             id:'zhuijia',
              handler:function(){
            	  selectusertreechecktaskwinshow("userid","username","node");  
//             	var _win = singleuserinforadiotree(Ext.get('databaseId').getValue());
//				_win.show();
//				_win.on("winsubmit",function(data){
//					addActor(data.userid);	
//					_win.close();		
//				});	
				
             }
		}],		
		renderTo:'topic-grid',
		store:sort,
		loadMask:true,
		height:$(window).height()-17,
		bbar:bbar,
		viewConfig:{
			forceFit:true
		}
	});
	
	sort.on('load', function() {    
		Ext.getCmp('zhuijia').setVisible(false);  
		sort.each(function(record) {
		    if (record.get('taskname') == '封发'){
		    	Ext.getCmp('zhuijia').setVisible(true); 
		    	return false;
		    }
		});		
	});
		
	sort.load({params:{start:0, limit: 23}});
	
}

/**
 * 改变流程候选人
 * @param {} taskid
 */
function changActor(taskid,userid){
	var url = Ext.get('changActorurl').getValue();
					Ext.Ajax.request({
						url:url,
						params:{
							taskid:taskid,
							actorid:userid
						},
						success:function(response, options){
							    var responseArray = Ext.util.JSON.decode(response.responseText);                                              
			                     if(responseArray.success==true){
			                        Ext.Msg.alert('信息','操作成功！',function(){
			                        	sort.reload({callback :function(){
			                        		grid.getView().refresh();	
			                        	}});										
			                        });			                     
			                     }
			                    else{
			                    	Ext.Msg.alert('信息','操作失败！');     
			                    } 
						}
					});
	
}

/**
 * 结束任务
 * @param {} taskid
 */
function endTask(taskid){
	Ext.MessageBox.show({
			           title:'消息',
			           msg: '是否执行此操作?',
			           buttons: Ext.MessageBox.YESNO,
			           fn: function(btn){
			           	  if(btn == 'yes'){
			           		var url = Ext.get('endTaskurl').getValue();
							Ext.Ajax.request({
								url:url,
								params:{
									taskid:taskid
								},
								success:function(response, options){
									    var responseArray = Ext.util.JSON.decode(response.responseText);                                              
					                     if(responseArray.success==true){
					                        Ext.Msg.alert('信息','操作成功！',function(){
					                        	sort.reload({callback :function(){
					                        		grid.getView().refresh();	
					                        	}});										
					                        });			                     
					                     }
					                    else{
					                    	Ext.Msg.alert('信息','操作失败！');     
					                    } 
								}
							});
			           	  }	
			           },
			           icon: Ext.MessageBox.QUESTION
       });
}

/**
 * 追加当前任务人
 * @param {} taskid
 */
function addActor(userid){
	var flowid =  Ext.get('flowid').getValue();
	var url = Ext.get('addTaskurl').getValue();
					Ext.Ajax.request({
						url:url,
						params:{
							flowid:flowid,
							actorid:userid
						},
						success:function(response, options){
							    var responseArray = Ext.util.JSON.decode(response.responseText);                                              
			                     if(responseArray.success==true){
			                        Ext.Msg.alert('信息','操作成功！',function(){
			                        	sort.reload({callback :function(){
			                        		grid.getView().refresh();	
			                        	}});										
			                        });			                     
			                     }
			                    else{
			                    	Ext.Msg.alert('信息','操作失败！');     
			                    } 
						}
					});
	
}


function changActorByUserId(taskid,taskName){
		var _win = null;
		
		if(taskName == "核稿"||taskName == "复核"||taskName == "部门主管会签"){
			_win = selectBuMenZhuGuan();
			_win.on("tradata",function(data){
				changActor(taskid,data.userId);				
			});
			_win.show();
		}
		else if(taskName == "办公室主任复核" || taskName == "二次办公室主任复核"){
			_win = selectBanGongShiGridWin();
			_win.on("tradata",function(data){
				changActor(taskid,data.userId);
			});
			_win.show();	
		}else if(taskName == "会签"||taskName == "签发"){
			_win = selectQianFaGridWin();
			_win.on("tradata",function(data){
				changActor(taskid,data.userId);
			});
			_win.show();
		}else {
			_win = selectSuoYouRenYuan();
			_win.on("tradata",function(data){
				changActor(taskid,data.userId);
			});
			_win.show();
		}
		
}	



/**
	查询部门主管
*/
function selectBuMenZhuGuan(){
	 var selectcheckusersort,userchecksm;
	 Ext.BLANK_IMAGE_URL=Ext.get('basePath').getValue()+"ajaxFramework/ext-2.1/resources/images/default/s.gif";
	 var url = Ext.get('basePath').getValue()+'tjsinfo/tjsoa/system/departmenttree.do';
	 var load = new Ext.tree.TreeLoader({
	 	dataUrl:url
	 });
	 var root = new Ext.tree.AsyncTreeNode({
	 	id:'0',
	 	text:'天津利达粮油有限公司'
	 })
	 var tree = new Ext.tree.TreePanel({
	 		x:0,
	 		y:0,	
        	autoScroll: true,
        	animate: true,
        	containerScroll: true,
        	border: true,
	        loader:load,	 
	        height:420,
	        width:230,
	        anchor:'0% 100%'
	    });
	tree.setRootNode(root); 
	tree.on('click',function(node){
	
		selectcheckusersort.load({
			params:{departmentid:node.id},
			callback:function(r,options,success){
				/**
				for(var i=0;i<r.length;i++)
				{
					var index = checkuserid.findBy(function(record,id){
						if(record.data.nodeid == node.id && record.data.userId ==  r[i].data.userId)
						{
							userchecksm.selectRecords([r[i]],true);
						}
					});
				}
				**/
			} 
		});
		checkoldnode=node.id;
	})
	/**
	 * 用户列表
	 */
	var userlisturl = Ext.get('basePath').getValue()+'tjsinfo/tjsoa/xingzhengfawen/selectUserByDepartmentListByDuty.do'
	selectcheckusersort = new Ext.data.JsonStore({
		url:userlisturl,
		fields:['userId','uuid','userName']
	});
	userchecksm  = new Ext.grid.CheckboxSelectionModel({
		singleSelect : true,
		handleMouseDown:Ext.emptyFn
	});
	var cm = new Ext.grid.ColumnModel([
		userchecksm,
		{header: "用户名", width: 75, dataIndex: 'userName',menuDisabled : true},
		{header: "userId", width: 75, dataIndex: 'userId',menuDisabled : true,hidden:true},
		{header: "uuid", width: 75, dataIndex: 'uuid',menuDisabled : true,hidden:true}
	]);
	var grid = new Ext.grid.GridPanel({
		x:tree.width,
	 	y:0,
		cm:cm,
		sm:userchecksm,
		width:270,
		height:420,
		anchor:'100% 100%',
		store:selectcheckusersort,
		border: true,
	   	viewConfig:{
			forceFit:true	
		}
	});
	var selectusercheckwin = new Ext.Window({
		layout:'absolute',
		title:'人员选择',
		width:520,
		height:500,
		modal:true,
		closeAction:'hide',
		items:[tree,grid],
		buttonAlign:'right',
		buttons:[{
			text:'保存',
			handler:function(){
				var userid="",username="",nodeid="";
				var rlolesarray = userchecksm.getSelections();
				var userId = rlolesarray[0].data.userId;
				var userName = rlolesarray[0].data.userName;				
				selectusercheckwin.hide();
				selectusercheckwin.fireEvent('tradata',{'userId':userId,'userName':userName});
			}
		},{
			text:'取消',
			handler:function(){
				selectusercheckwin.hide();		
			}
		}]
		
	})
	
	return selectusercheckwin;
}

/**
	查询所有人员
*/
function selectSuoYouRenYuan(){
	 var selectcheckusersort,userchecksm;
	 Ext.BLANK_IMAGE_URL=Ext.get('basePath').getValue()+"ajaxFramework/ext-2.1/resources/images/default/s.gif";
	 var url = Ext.get('basePath').getValue()+'tjsinfo/tjsoa/system/departmenttree.do';
	 var load = new Ext.tree.TreeLoader({
	 	dataUrl:url
	 });
	 var root = new Ext.tree.AsyncTreeNode({
	 	id:'0',
	 	text:'天津利达粮油有限公司'
	 })
	 var tree = new Ext.tree.TreePanel({
	 		x:0,
	 		y:0,	
        	autoScroll: true,
        	animate: true,
        	containerScroll: true,
        	border: true,
	        loader:load,	 
	        height:420,
	        width:230,
	        anchor:'0% 100%'
	    });
	tree.setRootNode(root); 
	tree.on('click',function(node){
	
		selectcheckusersort.load({
			params:{departmentid:node.id},
			callback:function(r,options,success){
				/**
				for(var i=0;i<r.length;i++)
				{
					var index = checkuserid.findBy(function(record,id){
						if(record.data.nodeid == node.id && record.data.userId ==  r[i].data.userId)
						{
							userchecksm.selectRecords([r[i]],true);
						}
					});
				}
				**/
			} 
		});
		checkoldnode=node.id;
	})
	/**
	 * 用户列表
	 */
	var userlisturl = Ext.get('basePath').getValue()+'tjsinfo/tjsoa/system/selectUserByDepartmentList.do'
	selectcheckusersort = new Ext.data.JsonStore({
		url:userlisturl,
		fields:['userId','uuid','userName']
	});
	userchecksm  = new Ext.grid.CheckboxSelectionModel({
		singleSelect : true,
		handleMouseDown:Ext.emptyFn
	});
	var cm = new Ext.grid.ColumnModel([
		userchecksm,
		{header: "用户名", width: 75, dataIndex: 'userName',menuDisabled : true},
		{header: "userId", width: 75, dataIndex: 'userId',menuDisabled : true,hidden:true},
		{header: "uuid", width: 75, dataIndex: 'uuid',menuDisabled : true,hidden:true}
	]);
	var grid = new Ext.grid.GridPanel({
		x:tree.width,
	 	y:0,
		cm:cm,
		sm:userchecksm,
		width:270,
		height:420,
		anchor:'100% 100%',
		store:selectcheckusersort,
		border: true,
	   	viewConfig:{
			forceFit:true	
		}
	});
	var selectusercheckwin = new Ext.Window({
		layout:'absolute',
		title:'人员选择',
		width:520,
		height:500,
		modal:true,
		closeAction:'hide',
		items:[tree,grid],
		buttonAlign:'right',
		buttons:[{
			text:'保存',
			handler:function(){
				var userid="",username="",nodeid="";
				var rlolesarray = userchecksm.getSelections();
				var userId = rlolesarray[0].data.userId;
				var userName = rlolesarray[0].data.userName;				
				selectusercheckwin.hide();
				selectusercheckwin.fireEvent('tradata',{'userId':userId,'userName':userName});
			}
		},{
			text:'取消',
			handler:function(){
				selectusercheckwin.hide();		
			}
		}]
		
	})
	
	return selectusercheckwin;
}

/**
 * 选择领导
 * @return {}
 */
function selectQianFaGridWin(){
	var _dutyname,_dutyid;
	
	var rolessm  = new Ext.grid.CheckboxSelectionModel({
		handleMouseDown:Ext.emptyFn,
		singleSelect : true,
		onMouseDown:function(e,t){
			if(t.className == 'x-grid3-row-checker x-grid3-row-radioBtn'){
				 	e.stopEvent();
		            var row = e.getTarget('.x-grid3-row');
		            if(row){
		                var index = row.rowIndex;
		                if(this.isSelected(index)){
		                    this.deselectRow(index);
		                }else{
		                    this.selectRow(index, true);
		                }
		            }
			}
		}
	});
	
	var _columnModle = new Ext.grid.ColumnModel({
		columns:[rolessm,{
			header: "姓名", sortable:true,dataIndex:'systemDuty.dutyName'
		}]
	});

	var _store = new Ext.data.JsonStore({
		fields:Ext.data.Record.create([{name:'systemDuty.dutyId',mapping:'userId'},
											{name:'systemDuty.dutyName',mapping:'userName'}
									 ]),
		url:Ext.basePath+'tjsinfo/tjsoa/xingzhengfawen/selectQianFaList.do',
		autoLoad:true
	});
	
	var _grid = new Ext.grid.GridPanel({		
		colModel:_columnModle,		
		frame:false,
		renderTo:Ext.get('showRegional'),
		sm: rolessm,
 		store:_store,
	    anchor:'100% 100%',
	    viewConfig:{
	    	forceFit: true
	    },
	    stripeRows:true,
	    loadMask: true
	});
	
	var _win = new Ext.ux.Window({
 					title:'选择人员',
 					width: 500,
	    			height: 300,
 					items:[_grid]
 	}); 
 	_win.on('datatra',function(_data){ 	
		var idarray =  _data.split(",");
		_store.on('load',function(){
			for(var i =0;i<idarray.length;i++){
				if(idarray[i] != ""){
				 	var index =  this.findBy(function(_r){			 		
				 		if(_r.get('systemDuty.dutyId') == idarray[i]){
				 			return true;
				 		}			 		
				 	});
				 	rolessm.selectRow(index,true);				 			 
				}			
			}
		});		
 	});
 	_win.show();
 	
 	var _gridEl = _grid.getEl();
	_gridEl.select('div.x-grid3-hd-checker').removeClass('x-grid3-hd-checker');
	
	_store.on('load', function() { //数据加载完毕替换为checkbox列增加一个class，然后我们在这个class中修改图片
			_gridEl.select("div[class=x-grid3-row-checker]").each(function(x) {
			x.addClass('x-grid3-row-radioBtn');
		})
	});
	
	_store.on('datachanged', function() { 
			//数据加载完毕替换为checkbox列增加一个class，然后我们在这个class中修改图片
			_gridEl.select("div[class=x-grid3-row-checker]").each(function(x) {
				x.addClass('x-grid3-row-radioBtn');
			})
	});
	
 	_win.on('winsubmint',function(_win){
		var dutyid = "";
		var dutyname = "";
		var dutyarray = new Array();
		dutyarray = rolessm.getSelections();		
		for(var i = 0;i<dutyarray.length;i++)
		{
				dutyid=dutyarray[i].get('systemDuty.dutyId') ;
				dutyname=dutyarray[i].get('systemDuty.dutyName') ;
		}
		
		_win.fireEvent('tradata',{'userId':dutyid,'userName':dutyname});
		_win.close();
 	});
 	_win.on('wincancel',function(_win){
		_win.close();			
 	});
 	
 	return _win;
}


/**
 * 选择办公室或党办主任
 * @return {}
 */
function selectBanGongShiGridWin(){
	var _dutyname,_dutyid;
	
	var rolessm  = new Ext.grid.CheckboxSelectionModel({
		handleMouseDown:Ext.emptyFn,
		singleSelect : true,
		onMouseDown:function(e,t){
			if(t.className == 'x-grid3-row-checker x-grid3-row-radioBtn'){
				 	e.stopEvent();
		            var row = e.getTarget('.x-grid3-row');
		            if(row){
		                var index = row.rowIndex;
		                if(this.isSelected(index)){
		                    this.deselectRow(index);
		                }else{
		                    this.selectRow(index, true);
		                }
		            }
			}
		}
	});
	
	var _columnModle = new Ext.grid.ColumnModel({
		columns:[rolessm,{
			header: "姓名", sortable:true,dataIndex:'systemDuty.dutyName'
		}]
	});

	var _store = new Ext.data.JsonStore({
		fields:Ext.data.Record.create([{name:'systemDuty.dutyId',mapping:'userId'},
											{name:'systemDuty.dutyName',mapping:'userName'}
									 ]),
		url:Ext.basePath+'tjsinfo/tjsoa/xingzhengfawen/selectBanGongShiList.do',
		autoLoad:true
	});
	
	var _grid = new Ext.grid.GridPanel({		
		colModel:_columnModle,		
		frame:false,
		renderTo:Ext.get('showRegional'),
		sm: rolessm,
 		store:_store,
	    anchor:'100% 100%',
	    viewConfig:{
	    	forceFit: true
	    },
	    stripeRows:true,
	    loadMask: true
	});
	
	var _win = new Ext.ux.Window({
 					title:'选择人员',
 					width: 500,
	    			height: 300,
 					items:[_grid]
 	}); 
 	_win.on('datatra',function(_data){ 	
		var idarray =  _data.split(",");
		_store.on('load',function(){
			for(var i =0;i<idarray.length;i++){
				if(idarray[i] != ""){
				 	var index =  this.findBy(function(_r){			 		
				 		if(_r.get('systemDuty.dutyId') == idarray[i]){
				 			return true;
				 		}			 		
				 	});
				 	rolessm.selectRow(index,true);				 			 
				}			
			}
		});		
 	});
 	_win.show();
 	
 	var _gridEl = _grid.getEl();
	_gridEl.select('div.x-grid3-hd-checker').removeClass('x-grid3-hd-checker');
	
	_store.on('load', function() { //数据加载完毕替换为checkbox列增加一个class，然后我们在这个class中修改图片
			_gridEl.select("div[class=x-grid3-row-checker]").each(function(x) {
			x.addClass('x-grid3-row-radioBtn');
		})
	});
	
	_store.on('datachanged', function() { 
			//数据加载完毕替换为checkbox列增加一个class，然后我们在这个class中修改图片
			_gridEl.select("div[class=x-grid3-row-checker]").each(function(x) {
				x.addClass('x-grid3-row-radioBtn');
			})
	});
	
 	_win.on('winsubmint',function(_win){
		var dutyid = "";
		var dutyname = "";
		var dutyarray = new Array();
		dutyarray = rolessm.getSelections();		
		for(var i = 0;i<dutyarray.length;i++)
		{
				dutyid=dutyarray[i].get('systemDuty.dutyId') ;
				dutyname=dutyarray[i].get('systemDuty.dutyName') ;
		}
		
		_win.fireEvent('tradata',{'userId':dutyid,'userName':dutyname});
		_win.close();
 	});
 	_win.on('wincancel',function(_win){
		_win.close();			
 	});
 	
 	return _win;
}